﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.IO;

namespace ChatQQ
{
    public partial class DlForm : Form
    {
        NetworkStream nws;
        public  static TcpClient client;
        //Thread t1;
        //Socket socke;
        public DlForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnquest_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient("192.168.1.2", 8098);
                nws = client.GetStream();
                string send = "in" + "|" + cbouid.Text + "|" + txtpwd.Text;//上线
                byte[] chat = Encoding.Default.GetBytes(send.ToCharArray());
                nws.Write(chat, 0, chat.Length);

                //t1 = new Thread(new ThreadStart(clientlisten));
                //t1.Start();
                clientlisten();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            
            
            
        }

        private void login()
        {
            MainQQForm mf = new MainQQForm(cbouid.Text, txtpwd.Text);
            mf.Show();
            this.Dispose(false);
        }

        private void btnexit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void clientlisten()
        {
            try
            {
                byte[] buffer = new byte[2048];
                nws.Read(buffer,0,buffer.Length);
                String cmd = Encoding.Default.GetString(buffer);
                String[] message = cmd.Split(new char[] { '|' }, 2);
                if (message[0] == "ok")
                {
                    this.login();
                }
                else if (message[0] == "no")
                {
                    MessageBox.Show("用户名密码有误！请确认！","错误！",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    return;
                }
                else if (message[0] == "have")
                {
                    MessageBox.Show("用户已经在线，如有问题请致电申诉！\n凤鸣天祥工作室 0771-5653965", "错误！", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void DlForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (nws!=null)
            {
                nws.Close();
            }

            //if (t1!=null)
            //{
                //t1.Abort();
            //}
            //if (socke!=null)
            //{
            //    socke.Close();
            //}
        }
    }
}